<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\controller\Frontend;
use think\Db;
use think\Exception;
use think\Lang;
use think\Response;

/**
 * 定时任务接口
 * @internal
 */
class Job extends Api
{
    protected $noNeedLogin = ['sendHyCoupon','sendTgCoupon'];
    protected $noNeedRight = ['*'];

    protected $excludeFields = "";

    /**
     * 发送会员补贴消费券 每周1的10点开始发放 增加消费券发放日志 增加用户消费券 累加用户消费券金额
     */
    public function sendHyCoupon()
    {
        //判断token
        $token = $this->request->request('token');
        if($token != "3257b8e0f9854efeb7f56d0c9c92d054") {
            $this->error("1");
        }

        $couponList = model('app\api\model\wanlshop\Coupon')
            ->where('type', '=', 'hybt')
            ->where('sendtime', '<=', time())
            ->where('surplus', '>', 0)
            ->where('deletetime', 'null')
            ->select();
        foreach ($couponList as $coupon) {
            $maxQx = 52;
            $perQx = round($coupon["price"]/$maxQx, 2);
            $perQxLj = 0;
            $realQx = 0;
            for ($i = 0; $i < $maxQx; $i++) {
                $perQxLj += $perQx;
                if($perQxLj >= $coupon["price"]) {
                    $realQx = $i+1;
                    break;
                }
            }

            //会遇到每期金额偏少，不足总金额情况，需要给每期金额加上0.01，然后继续计算
            if ($realQx == 0) {
                $perQx += 0.01;
            }

            $curAmount = $perQx;
            //最后一期用剩余金额
            if ($coupon["alreadygrant"] == $maxQx - 1) {
                $curAmount = $coupon["price"] - $perQx * ($maxQx - 1);
            }

            Db::startTrans();
            try {
                // 修改消费券已领取数量，剩余数量，下次发送时间
                //下周1的10点
                $mondayThisWeek = strtotime('Monday this week');
                $mondayNextWeek = strtotime('next Monday', $mondayThisWeek);
                $nextMonday10AM = strtotime('+10 hours', $mondayNextWeek);
                Db::execute("UPDATE yz_wanlshop_coupon SET alreadygrant = alreadygrant +1, surplus = surplus -1, sendtime  = {$nextMonday10AM} WHERE id = " . $coupon['id']);

                // 增加消费券发放日志
                $qx = $coupon["alreadygrant"]+1;
                model('app\api\model\wanlshop\CouponReceive')->create([
                    'coupon_id' => $coupon['id'],
                    'coupon_no' => $coupon['id'] . '_' . $qx,
                    'user_id'=> $coupon['user_id'],
                    'shop_id'=> $coupon['shop_id'],
                    'order_id'=> $coupon['order_id'],
                    'order_no'=> $coupon['order_no'],
                    'type' => 'hybt',
                    'name' => "会员补贴消费券第{$qx}期",
                    'price'=> $curAmount,
                    'gl_id'=> $coupon['gl_id'],
                ]);

                $userinfo =  model('app\common\model\User')
                    ->where(['id' => $coupon['user_id']])
                    ->field('coupon_num')
                    ->find();

                // 消费券
                model('app\common\model\ConsumCard')->create([
                    'user_id'=> $coupon['user_id'],
                    'money'=> $curAmount,
                    'balance' => $userinfo['coupon_num'] + $curAmount,
                    'get_type' => 3,
                    'order_id' => $coupon['order_id'],
                    'order_user_id' => $coupon['user_id'],
                    'order_shop_id' => $coupon['shop_id'],
                    'order_no' => $coupon['order_no']
                ]);

                // 累加用户消费券金额
                Db::execute("UPDATE yz_user SET coupon_num = coupon_num +{$curAmount} WHERE id = {$coupon['user_id']}");

                Db::commit(); // 提交事务
            } catch (Exception $e) {
                Db::rollback(); // 回滚事务
                continue;
            }
        }

        $this->success();
    }
}
